package com.rimi.service.impl;

import com.rimi.bean.Page;
import com.rimi.bean.Role;
import com.rimi.bean.User;
import com.rimi.dao.RoleDao;
import com.rimi.dao.UserDao;
import com.rimi.dao.impl.RoleDaoImpl;
import com.rimi.dao.impl.UserDaoImpl;
import com.rimi.service.RoleService;
import com.rimi.service.UserService;
import com.rimi.util.StringUtils;

import java.util.List;

/**
 * @author chengliang
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao;
    private RoleDao roleDao;

    public UserServiceImpl(){
        userDao = new UserDaoImpl();
        roleDao = new RoleDaoImpl();
    }

    @Override
    public User login(String loginName, String password) {
        //检查参数是否存在问题
        if(StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)){
            return null;
        }
        User user = userDao.selectUserByLoginName(loginName);
        if(user == null){
            return null;
        }
        if (!user.getUserPassword().equals(password)){
            return null;
        }
        return user;
    }

    @Override
    public List<User> getUserListBy(User user, Page page) {
        List<User> userList = userDao.selectUserListBy(user, page);
        for (User u : userList) {
            Role role = roleDao.selectRoleById(u.getRoleId());
            u.setRole(role);
            System.out.println(u.getRole());
        }
        return userList;
    }

    @Override
    public boolean updateEnable(String userId, String userEnable) {
        return userDao.updateEnable(StringUtils.stringToNumber(userId),StringUtils.stringToNumber(userEnable));
    }

    @Override
    public boolean dropUserBy(String ids) {
        if (StringUtils.isEmpty(ids)){
            return false;
        }
        //通过 ，分割ID
        String[] stringIds = ids.split(",");
        return userDao.deleteBy(stringIds);
    }

    @Override
    public boolean saveUser(User user) {
        return userDao.insertUser(user);
    }

    @Override
    public User getUserById(String id) {
        if(StringUtils.isEmpty(id)){
            return null;
        }
        return userDao.selectUserById(id);
    }

    @Override
    public boolean updateUser(User user) {
        return userDao.updateUser(user);
    }

    @Override
    public int countUserBy(User user) {
        return userDao.countUserBy(user);
    }

    @Override
    public List<User> getUserListByIds(String ids) {
        if(StringUtils.isEmpty(ids)){
            return null;
        }
        return userDao.selectUserListByIds(ids);
    }
}
